﻿using System.Linq;
using System.Web.Mvc;
using SportsStore.Domain.Abstract;
using SportsStore.Domain.Entities;
using SportsStore.WebUI.Models;

namespace SportsStore.WebUI.Controllers
{
    public class ProductController : Controller
    {
        public int PageSize = 4;
        private readonly IProductRepository repository;

        public ProductController(IProductRepository productRepository)
        {
            repository = productRepository;
        }

        public ViewResult List(string category,int page = 1)
        {
            var ct = category;
            var test = repository
                .Products.Where(p => category == null || p.Category == category)
                .OrderBy(p => p.ProductID)
                .Skip((page - 1)*PageSize).Take(PageSize);

            var viewModel = new ProductsListViewModel
                                                {
                                                    PagingInfo = new PagingInfo
                                                                    {
                                                                        CurrentPage = page,
                                                                        ItemsPerPage = PageSize,
                                                                        TotalItems = category == null ?
                                                                            repository.Products.Count() :
                                                                            repository.Products.Count(e => e.Category == category)
                                                                    },

                                                    Products = repository
                                                    .Products.Where(p => category == null || p.Category == category)
                                                    .OrderBy(p => p.ProductID)
                                                    .Skip((page - 1)*PageSize).Take(PageSize)

                                                    ,CurrentCategory = category
                                                };

            return View(viewModel);
        }

        public FileContentResult GetImage(int productId)
        {
            Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productId);
            if (prod != null)
            {
                return File(prod.ImageData, prod.ImageMimeType);
            }
            return null;
        }
    }
}
